<?php
session_start();
require_once 'config/database.php';
require_once 'includes/EmailNotification.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validate input
if (empty($_POST['car_id']) || empty($_POST['message'])) {
    echo json_encode(['success' => false, 'message' => 'Required fields are missing']);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login to submit an inquiry']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

try {
    // Get user details
    $user_query = "SELECT first_name, last_name, email, phone FROM users WHERE id = ?";
    $user_stmt = $db->prepare($user_query);
    $user_stmt->execute([$_SESSION['user_id']]);
    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception("User not found");
    }

    // Get car details
    $car_query = "SELECT c.*, b.name as brand_name, m.name as model_name 
                  FROM cars c 
                  LEFT JOIN brands b ON c.brand_id = b.id 
                  LEFT JOIN models m ON c.model_id = m.id 
                  WHERE c.id = ?";
    $car_stmt = $db->prepare($car_query);
    $car_stmt->execute([$_POST['car_id']]);
    $car = $car_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$car) {
        throw new Exception("Car not found");
    }

    // Insert the inquiry - Core functionality
    $insert_query = "INSERT INTO inquiries (
        user_id,
        name,
        email,
        phone,
        car_id,
        message,
        status
    ) VALUES (?, ?, ?, ?, ?, ?, 'New')";
    
    $stmt = $db->prepare($insert_query);
    $result = $stmt->execute([
        $_SESSION['user_id'],
        $user['first_name'] . ' ' . $user['last_name'],
        $user['email'],
        $user['phone'],
        $_POST['car_id'],
        $_POST['message']
    ]);

    if (!$result) {
        throw new Exception("Failed to insert inquiry");
    }

    // Try to send emails, but don't let failure stop the process
    try {
        $admin_email = "your-admin-email@example.com"; // Replace with your actual admin email
        
        // Create email notification
        $emailNotification = new EmailNotification($admin_email);
        
        // Format the email message
        $admin_subject = "New Car Inquiry: " . $car['title'];
        
        $admin_message = "New Car Inquiry Details:\n\n";
        $admin_message .= "Inquirer Information:\n";
        $admin_message .= "----------------\n";
        $admin_message .= "Name: " . $user['first_name'] . ' ' . $user['last_name'] . "\n";
        $admin_message .= "Email: " . $user['email'] . "\n";
        $admin_message .= "Phone: " . $user['phone'] . "\n\n";
        
        $admin_message .= "Car Information:\n";
        $admin_message .= "----------------\n";
        $admin_message .= "Car: " . $car['brand_name'] . " " . $car['model_name'] . " " . $car['year'] . "\n";
        $admin_message .= "Price: $" . number_format($car['price'], 2) . "\n";
        $admin_message .= "Car ID: " . $_POST['car_id'] . "\n\n";
        
        $admin_message .= "Message:\n";
        $admin_message .= "----------------\n";
        $admin_message .= $_POST['message'] . "\n\n";
        
        $admin_message .= "View Details:\n";
        $admin_message .= "----------------\n";
        $admin_message .= "View this inquiry in the admin panel: " . 
                         (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . 
                         $_SERVER['HTTP_HOST'] . "/admin/inquiries.php?id=" . $_POST['car_id'];
        
        // Try to send admin email
        $emailNotification->sendEmail($admin_subject, $admin_message);
        
        // Try to send user confirmation email
        $user_notification = new EmailNotification($user['email']);
        $user_subject = "Your Inquiry Confirmation";
        $user_message = "Dear " . $user['first_name'] . ' ' . $user['last_name'] . ",\n\n";
        $user_message .= "Thank you for your inquiry about " . $car['brand_name'] . " " . $car['model_name'] . " " . $car['year'] . ".\n\n";
        $user_message .= "We have received your message and will get back to you shortly.\n\n";
        $user_message .= "Your inquiry details:\n";
        $user_message .= "----------------\n";
        $user_message .= "Message: " . $_POST['message'] . "\n\n";
        $user_message .= "Best regards,\n";
        $user_message .= "Your Dealership Team";

        $user_notification->sendEmail($user_subject, $user_message);
    } catch (Exception $emailError) {
        // Just log the email error silently
        error_log("Email sending failed: " . $emailError->getMessage());
    }

    // Return success regardless of email status
    echo json_encode([
        'success' => true,
        'message' => 'Your inquiry has been submitted successfully. We will contact you soon.'
    ]);
    exit;

} catch (Exception $e) {
    error_log("Inquiry Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error submitting inquiry. Please try again later.'
    ]);
    exit;
}
?> 